#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include "database/Client.hpp"
#include "TCPServer.h"
#include "IntegrityDatas.h"
#include "Protocol.h"

void CSProtocol::Login::receiveTreat(TCPConnection &connexion, IData *udata)
{
  CSProtocol::Login *data = static_cast<CSProtocol::Login*>(udata);
  if (!data)
    return;
  CSProtocol::Header header = CSProtocol::Header();
  header.spontaneous = false;
  IData *pcmd;
  if (IntegrityDatas::checkLogin(data->login)
      && IntegrityDatas::checkPass(data->pass)
      && ((connexion.getServer())->getDB()).clientExist(data->login)
      && ((connexion.getServer())->getDB()).loginMatchPass(data->login, data->pass))
    {
      Client *clt = ((connexion.getServer())->getDB()).getClientByLogin(data->login);
      if (clt)
	{
	  connexion.setAuthenticate(true);
	  connexion.setClient(clt);
	  clt->setConnexion(&connexion);
	  boost::asio::ip::tcp::endpoint remote_ep = connexion.socket().remote_endpoint();
	  boost::asio::ip::address remote_ad = remote_ep.address();
	  std::string s = remote_ad.to_string();
	  (connexion.getClient())->setIp(s);
	  header.code = CSProtocol::Ok::code;
	  CSProtocol::Ok command = CSProtocol::Ok();
	  pcmd = &command;
	  strcpy(command.what, "Login succesfull.");
	  header.dataLength = sizeof(CSProtocol::Ok);
	}
    }
  else
    {
      header.code = CSProtocol::Ko::code;
      CSProtocol::Ko command = CSProtocol::Ko();
      strcpy(command.what, "Login failed.");
      pcmd = &command;
      header.dataLength = sizeof(CSProtocol::Ko);
    }
  connexion.write(header, *pcmd);
}

void CSProtocol::Login::sendTreat(TCPConnection &connexion)
{
}
